import Dialog from 'tdesign-miniprogram/dialog/index';
import Toast from 'tdesign-miniprogram/toast/index';
import { fetchCartGroupData } from '../../services/cart/cart';
import { getUserId, getAllGoodsList, getCurGoodsInfo, getStudentsList, getOpenId, getSelectedSchoolId, getSelectedSchoolData, getSelectedStudentId } from '../../userData/userData';
Page({
  data: {
    cartGroupData: null,
    newCartData: null,
  },

  // 调用自定义tabbar的init函数，使页面与tabbar激活状态保持一致
  onShow () {
    this.getTabBar().init();

    this.initCartPage();
  },

  onLoad () {
    this.refreshData();
  },

  initCartPage () {
    console.log("initCartPage----------");
    var userid = getUserId();
    var insid = getSelectedSchoolData()._id;
    var allGoodsListData = getAllGoodsList()
    var students = getStudentsList()
    console.log(userid, insid);
    wx.cloud.callFunction({
      name: "shop_getUserCartforInstitution",
      data: {
        user_id: userid,
        institution_id: insid,
      }
    }).then(res => {
      console.log(res)
      const cartData = {}
      cartData.goodlist = res.result
      cartData.stu_goodList = {}
      var totalPrice = 0

      console.log(students)
      console.log(allGoodsListData)
      cartData.stu_goodList.allGoodsList = []
      cartData.stu_goodList.allStuList = []
      for (var i in students) {
        var list = {}
        list.name = students[i].name
        list.promotionGoodsList = []

        var proGoodsList = {}
        proGoodsList.goodsPromotionList = []
        proGoodsList.doorSillRemain = null
        proGoodsList.promotionStatus = 3
        proGoodsList.promotionId = "159174555838121985"
        proGoodsList.promotionCode = "MERCHANT"
        proGoodsList.isNeedAddOnShop = 0
        list.promotionGoodsList.push(proGoodsList)
        cartData.stu_goodList.allStuList.push(list)
      }
      console.log(cartData.stu_goodList.allStuList)
      for (const goods of cartData.goodlist) {
        //todo 根据商品id查询价格 goods.g_id 
        var goodsInfo = getCurGoodsInfo(goods.g_id)
        if (goodsInfo != null) {
          goods.price = goodsInfo.price;
          totalPrice += goods.price * goods.number
          goods.title = goodsInfo.title
          goods.description = goodsInfo.description
          goods.thumb = goodsInfo.img
          goods.quantity = goods.number
          goods.specInfo = goods.parameter
          goods.stockQuantity = goodsInfo.number
          // goods.specInfo = [{
          //   specTitle: '颜色',
          //   specValue: goods.parameter,
          // },
          // {
          //   specTitle: '类型',
          //   specValue: '',
          // },]
          cartData.stu_goodList.allGoodsList.push(goods)
          for (var i in students) {
            if (students[i]._id == goods.s_id) {
              cartData.stu_goodList.allStuList[i].promotionGoodsList[0].goodsPromotionList.push(goods)

            }

          }
        }


      }

      cartData.totalPrice = totalPrice
      this.setData({ newCartData: cartData });
      console.log(this.data.newCartData)
    })
    console.log(this.data.newCartData)

  },

  refreshData () {

    this.getCartGroupData().then((res) => {
      let isEmpty = true;
      const cartGroupData = res.data;
      // 一些组件中需要的字段可能接口并没有返回，或者返回的数据结构与预期不一致，需要在此先对数据做一些处理
      // 统计门店下加购的商品是否全选、是否存在缺货/无货
      for (const store of cartGroupData.storeGoods) {
        store.isSelected = true; // 该门店已加购商品是否全选
        store.storeStockShortage = false; // 该门店已加购商品是否存在库存不足
        if (!store.shortageGoodsList) {
          store.shortageGoodsList = []; // 该门店已加购商品如果库存为0需单独分组
        }
        for (const activity of store.promotionGoodsList) {
          activity.goodsPromotionList = activity.goodsPromotionList.filter((goods) => {
            goods.originPrice = undefined;

            // 统计是否有加购数大于库存数的商品
            if (goods.quantity > goods.stockQuantity) {
              store.storeStockShortage = true;
            }
            // 统计是否全选
            if (!goods.isSelected) {
              store.isSelected = false;
            }
            // 库存为0（无货）的商品单独分组
            if (goods.stockQuantity > 0) {
              return true;
            }
            store.shortageGoodsList.push(goods);
            return false;
          });

          if (activity.goodsPromotionList.length > 0) {
            isEmpty = false;
          }
        }
        if (store.shortageGoodsList.length > 0) {
          isEmpty = false;
        }
      }
      cartGroupData.invalidGoodItems = cartGroupData.invalidGoodItems.map((goods) => {
        goods.originPrice = undefined;
        return goods;
      });
      cartGroupData.isNotEmpty = !isEmpty;
      this.setData({ cartGroupData: cartGroupData });
    });
  },

  //获取该用户对某一个具体学校的所有购物车(所有学生) 成功返回数组:Lid;"sid:g_id:"",number:"“)
  getUserCart (userId, institutionId) {
    return wx.cloud.callFunction({
      name: "shop_getUserCartforinstitution",
      data: {
        user_id: userId,
        institution_id: institutionId,
      }
    }).then(res => { console.log(res.result) }).catch(console.error)
  },

  //添加购物车   成功则返回数组:data[0J: Lid:",s_id:gid:"”,number"”)
  addCart (studentId, goodId, params) {
    wx.cloud.callFunction({
      name: "shop_addCart",
      data: {
        student_id: studentId,
        good_id: goodId,
        number: 1,
        parameter: params,
      }
    }).then(res => { console.log(res.result) }).catch(console.error)
  },

  //更新购物车  成功则返回数组:data[0]:(id:"”sid“gid:"number"”.) 无更新则返回0
  updateCart (cartId, studentId, goodId, num) {
    wx.cloud.callFunction({
      name: "shop_updateCart",
      data: {
        cart_id: cartId,
        student_id: studentId,
        good_id: goodId,
        number: num
      }
    }).then(res => { console.log(res.result) }).catch(console.error)
  },

  //删除购物车   成功状态:resresult.statsremoved==1
  deleteCart (cartId) {
    wx.cloud.callFunction({
      name: "shop_deleteCart",
      data: {
        cart_id: cartId,
      }
    }).then(res => { console.log(res.result) }).catch(console.error)
  },

  findGoods (spuId, skuId) {
    let currentStore;
    let currentActivity;
    let currentGoods;
    const { storeGoods } = this.data.cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        for (const goods of activity.goodsPromotionList) {
          if (goods.spuId === spuId && goods.skuId === skuId) {
            currentStore = store;
            currentActivity = currentActivity;
            currentGoods = goods;
            return {
              currentStore,
              currentActivity,
              currentGoods,
            };
          }
        }
      }
    }
    return {
      currentStore,
      currentActivity,
      currentGoods,
    };
  },

  // 注：实际场景时应该调用接口获取购物车数据
  getCartGroupData () {
    const { cartGroupData } = this.data;
    if (!cartGroupData) {
      return fetchCartGroupData();
    }
    return Promise.resolve({ data: cartGroupData });
  },

  // 选择单个商品
  // 注：实际场景时应该调用接口更改选中状态
  selectGoodsService ({ spuId, skuId, isSelected }) {
    this.findGoods(spuId, skuId).currentGoods.isSelected = isSelected;
    return Promise.resolve();
  },

  // 全选门店
  // 注：实际场景时应该调用接口更改选中状态
  selectStoreService ({ storeId, isSelected }) {
    const currentStore = this.data.cartGroupData.storeGoods.find((s) => s.storeId === storeId);
    currentStore.isSelected = isSelected;
    currentStore.promotionGoodsList.forEach((activity) => {
      activity.goodsPromotionList.forEach((goods) => {
        goods.isSelected = isSelected;
      });
    });
    return Promise.resolve();
  },

  // 加购数量变更
  // 注：实际场景时应该调用接口
  changeQuantityService ({ spuId, skuId, quantity }) {
    this.findGoods(spuId, skuId).currentGoods.quantity = quantity;
    return Promise.resolve();
  },

  // 删除加购商品
  // 注：实际场景时应该调用接口
  deleteGoodsService ({ spuId, skuId }) {
    function deleteGoods (group) {
      for (const gindex in group) {
        const goods = group[gindex];
        if (goods.spuId === spuId && goods.skuId === skuId) {
          group.splice(gindex, 1);
          return gindex;
        }
      }
      return -1;
    }
    const { storeGoods, invalidGoodItems } = this.data.cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        if (deleteGoods(activity.goodsPromotionList) > -1) {
          return Promise.resolve();
        }
      }
      if (deleteGoods(store.shortageGoodsList) > -1) {
        return Promise.resolve();
      }
    }
    if (deleteGoods(invalidGoodItems) > -1) {
      return Promise.resolve();
    }
    return Promise.reject();
  },

  // 清空失效商品
  // 注：实际场景时应该调用接口
  clearInvalidGoodsService () {
    this.data.cartGroupData.invalidGoodItems = [];
    return Promise.resolve();
  },

  onGoodsSelect (e) {
    const {
      goods: { spuId, skuId },
      isSelected,
    } = e.detail;
    const { currentGoods } = this.findGoods(spuId, skuId);
    Toast({
      context: this,
      selector: '#t-toast',
      message: `${isSelected ? '选择' : '取消'}"${currentGoods.title.length > 5 ? `${currentGoods.title.slice(0, 5)}...` : currentGoods.title
        }"`,
      icon: '',
    });
    this.selectGoodsService({ spuId, skuId, isSelected }).then(() => this.refreshData());
  },

  onStoreSelect (e) {
    const {
      store: { storeId },
      isSelected,
    } = e.detail;
    this.selectStoreService({ storeId, isSelected }).then(() => this.refreshData());
  },

  onQuantityChange (e) {
    console.log("-----------------------")
    console.log(e)

    // const {
    //   goods: goods,
    //   quantity,
    // } = e.detail;
    var goods = e.detail.goods
    var quantity = e.detail.quantity
    console.log(quantity)
    var goodsInfo = getCurGoodsInfo(goods.g_id)//this.findGoods(spuId, skuId);
    console.log(goodsInfo)
    const stockQuantity = goodsInfo.number > 0 ? goodsInfo.number : 0; // 避免后端返回的是-1
    // 加购数量超过库存数量
    if (quantity > stockQuantity) {
      // 加购数量等于库存数量的情况下继续加购
      if (currentGoods.quantity === stockQuantity && quantity - stockQuantity === 1) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '当前商品库存不足',
        });
        return;
      }
      // Dialog.confirm({
      //   title: '商品库存不足',
      //   content: `当前商品库存不足，最大可购买数量为${stockQuantity}件`,
      //   confirmBtn: '修改为最大可购买数量',
      //   cancelBtn: '取消',
      // })
      //   .then(() => {
      //     this.changeQuantityService({
      //       spuId,
      //       skuId,
      //       quantity: stockQuantity,
      //     }).then(() => this.refreshData());
      //   })
      //   .catch(() => { });
      return;
    }
    wx.cloud.callFunction({
      name: "shop_updateCart",
      data: {
        cart_id: goods._id,
        student_id: goods.s_id,
        good_id: goods.g_id,
        number: quantity,
        parameter: goods.specInfo
      }
    }).then(res => {
      console.log(res.result);
      this.initCartPage()
    })
    // this.changeQuantityService({ spuId, skuId, quantity }).then(() => this.refreshData());
  },

  goCollect () {
    /** 活动肯定有一个活动ID，用来获取活动banner，活动商品列表等 */
    const promotionID = '123';
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },

  goGoodsDetail (e) {
    const { spuId, storeId } = e.detail.goods;
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}&storeId=${storeId}`,
    });
  },

  clearInvalidGoods () {
    // 实际场景时应该调用接口清空失效商品
    this.clearInvalidGoodsService().then(() => this.refreshData());
  },

  onGoodsDelete (e) {
    // const {
    //   goods: { spuId, skuId },
    // } = e.detail;
    var cartInfo = e.detail.goods
    // wx.cloud.callFunction({
    //   name: "shop_deleteCart",
    //   data: {
    //     cart_id: cartInfo._id
    //   }
    // }).then(res => {
    //   console.log(res.result);
    //   this.initCartPage()
    // })
    const dialogConfig = {
      context: this,
      show: true,
      title: '确认删除该商品吗',
      content: ' ',
      confirmBtn: '确定',
      closeBtn: '取消',
      cancelBtn: '取消'
    };
    console.log(e.detail)
    Dialog.confirm(dialogConfig)
      .then(() => {
        wx.cloud.callFunction({
          name: "shop_deleteCart",
          data: {
            cart_id: cartInfo._id
          }
        }).then(res => {
          console.log(res.result);
          this.initCartPage()
        })
      })
      .catch(() => console.log('点击了取消'))
      .finally(() => Dialog.close());
  },

  onSelectAll (event) {
    const { isAllSelected } = event?.detail ?? {};
    Toast({
      context: this,
      selector: '#t-toast',
      message: `${isAllSelected ? '取消' : '点击'}了全选按钮`,
    });
    // 调用接口改变全选
  },

  onToSettle () {
    //去结算点击事件
    wx.cloud.callFunction({
      name: 'pay',
      data: {
        body: '支付',
        detail: JSON.stringify(this.data.newCartData.goodlist),
        attach: '',
        totalFee: this.data.newCartData.totalPrice * 100
      },
      success: res => {
        if (res.result.errCode == 0) {
          const payment = res.result.payment
          console.log(res)
          wx.requestPayment({
            ...payment,
            success (res) {
              console.log('pay success', res)
              this.initCartPage()
            },
            fail (err) {
              console.warn('pay fail', err)
            }
          })
          for (const goods of this.data.newCartData.goodlist) {
            wx.cloud.callFunction({
              name: "shop_deleteCart",
              data: {
                cart_id: goods._id
              }
            }).then(res => {
              console.log(res.result);
              this.initCartPage()
            })
          }
        } else if (res.result.errCode == -1) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: res.result.errMsg,
          });
        }
      },
      fail: console.error,
    })
  },
  onGotoHome () {
    wx.switchTab({ url: '/pages/home/home' });
  },
});
